package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.function.Consumer;

/**
 * @author ybw
 * @version 1.0
 * @date 2021/12/11 20:22
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {
  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    // 获取请求对象
    ServerHttpRequest request = exchange.getRequest();
    // 获取响应对象
    ServerHttpResponse response = exchange.getResponse();
    // 获取路径参数
    URI uri = request.getURI();
    if (uri.getPath().contains("/login")) {
      // 登录请求，直接放行
      return chain.filter(exchange);
    }
    // 打印日志
    log.info("拦截到请求{}",uri);
    // 获取token
    String token = request.getHeaders().getFirst("token");
    // 判断token是否合法
    try {
      Claims claims = AppJwtUtil.getClaimsBody(token);
      int count = AppJwtUtil.verifyToken(claims);
      if (count == 1 || count == 2) {
        // 不合法
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
      }

      // 解析token，获取用户id
      Object userId = claims.get("id");
      // 将用户id存入header中
      ServerHttpRequest httpRequest =
          request
              .mutate()
              .headers(httpHeaders -> httpHeaders.add("userId", userId.toString()))
              .build();
      exchange.mutate().request(httpRequest);
    } catch (Exception e) {
      response.setStatusCode(HttpStatus.UNAUTHORIZED);
      return response.setComplete();
    }
    // 放行
    return chain.filter(exchange);
  }

  @Override
  public int getOrder() {
    return 0;
  }
}
